package com.cf.message.service;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.cf.expire.ExpireService;
import com.cf.util.ObjectJsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * boot-message-PhoneCodeService
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/7/26 下午 02:18
 */
@Slf4j
@Service
public class PhoneCodeService {

    private String PHONE_KEY_PREFIX = "PHONE_KEY_PREFIX_";

    @Autowired
    private ExpireService expireService;

    @Autowired
    private SmsSendService smsSendService;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @param sign
     * @param smsTemplate
     * @return
     */
    public boolean sendSmsCode(String phone, String sign, String smsTemplate, Integer timeLast) {
        String phoneCode = RandomUtil.randomString("0123456789", 6);
        SendSmsResponse sendSmsResponse = smsSendService.sendSms(phone, sign, smsTemplate, ObjectJsonUtil.toString(MapUtil.of("code", phoneCode)));
        if ("OK".equals(sendSmsResponse.getCode())) {
            expireService.setExpire(PHONE_KEY_PREFIX + phone, phoneCode, timeLast);
            return true;
        } else {
            log.warn("短信接口发送失败！【{}】", ObjectJsonUtil.toString(sendSmsResponse));
            return false;
        }
    }

    /**
     * 检测
     *
     * @param phone
     * @param code
     * @return
     */
    public boolean checkPhoneCode(String phone, String code) {
        if (StringUtils.isEmpty(code))
            return false;
        String expire = expireService.getExpire(PHONE_KEY_PREFIX + phone);
        return code.equals(expire);
    }

    /**
     * 删除
     *
     * @param phone
     */
    public void del(String phone) {
        expireService.del(PHONE_KEY_PREFIX + phone);
    }

}
